package com.newshub.app.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.newshub.app.data.model.News
import com.newshub.app.data.repository.NewsRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class HomeViewModel : ViewModel() {
    
    private val newsRepository = NewsRepository
    
    private val _newsList = MutableLiveData<List<News>>()
    val newsList: LiveData<List<News>> = _newsList
    
    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading
    
    private val _error = MutableLiveData<String?>()
    val error: LiveData<String?> = _error
    
    fun loadHeadlineNews() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                _error.value = null
                
                // 使用Repository方法获取新闻，会自动设置收藏状态
                val newsList = withContext(Dispatchers.IO) {
                    newsRepository.getHeadlineNews(0, 20).blockingFirst()
                }
                _newsList.value = newsList
                _isLoading.value = false
            } catch (e: Exception) {
                _error.value = e.message
                _isLoading.value = false
            }
        }
    }
    
    fun refreshNews() {
        loadHeadlineNews()
    }
    
    fun toggleFavorite(news: News) {
        viewModelScope.launch {
            try {
                // 根据当前收藏状态调用相应方法
                if (news.isFavorite) {
                    newsRepository.removeFromFavorite(news.docid)
                } else {
                    newsRepository.addToFavorite(news)
                }
                
                // 更新本地新闻列表中的收藏状态
                val currentList = _newsList.value ?: emptyList()
                val updatedList = currentList.map { item ->
                    if (item.docid == news.docid) {
                        item.copy(isFavorite = !item.isFavorite)
                    } else {
                        item
                    }
                }
                _newsList.value = updatedList
            } catch (e: Exception) {
                _error.value = "更新收藏状态失败: ${e.message}"
            }
        }
    }
}